<?php
/**
 * @version		$Id: contentlink.php 10381 2008-06-01 03:35:53Z yopensource $
 * @package		Joomla
 * @subpackage	Content
 * @copyright	Copyright (C) 2005 - 2008 YOS. All rights reserved.
 * @license		Commercial
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );

jimport('joomla.application.component.model');

// Set the table directory
JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');

/**
 * Weblinks Component Weblink Model
 *
 * @package		Joomla
 * @subpackage	Content
 * @since 1.5
 */
class YOS_NewsModelContentLink extends JModel
{	
	function getData(){		
		global $mainframe;
		// Initialize variables
		$doTask 	= JRequest::getCmd('task',null);
		
		$db			=& JFactory::getDBO();
		$user 		=& JFactory::getUser();
		$uid		= $user->get('id');
		$option		= JRequest::getCmd( 'option' );
		$cid		= JRequest::getVar( 'cid', array(0), '', 'array' );
	
		JArrayHelper::toInteger($cid, array(0));
		
		$edit		=	(strtolower($doTask) == 'news.edit') || ($cid[0]);
	
		$row =& JTable::getInstance('YOS_News_Crawler','Table');
		// load the row from the db table
		if ($edit)
			$row->load( $cid[0] );
			
		
	
//		 fail if checked out not by 'me'
		if ( JTable::isCheckedOut($user->get ('id'), $row->checked_out )) {
			$msg = JText::sprintf( 'DESCBEINGEDITTED', JText::_( 'The News Crawler' ), $row->link );
			$mainframe->redirect( "index.php?option=$option&task=linkmanager", $msg );
		}
		
		if ( $edit ) {
			$row->checkout( $user->get('id'));			
			$row->ads			=	base64_decode($row->ads);
			$row->link			=	base64_decode($row->link);
			$row->getlink_reg	=	base64_decode($row->getlink_reg);
			$row->gettitle_reg	=	base64_decode($row->gettitle_reg);
			$row->getintro_reg	=	base64_decode($row->getintro_reg);
			$row->getfull_reg	=	base64_decode($row->getfull_reg);
			$row->find_replace_intro	=	base64_decode($row->find_replace_intro);
			$row->find_replace_intro_afterencode	=	base64_decode($row->find_replace_intro_afterencode);
			$row->find_replace_full	=	base64_decode($row->find_replace_full);
			$row->find_replace_full_afterencode	=	base64_decode($row->find_replace_full_afterencode);
			$row->find_replace_plugin	=	base64_decode($row->find_replace_plugin);
			$row->find_replace_plugin_afterencode	=	base64_decode($row->find_replace_plugin_afterencode);
			$row->nextpage_reg	=	base64_decode($row->nextpage_reg);
			$row->pagebreak_reg	=	base64_decode($row->pagebreak_reg);
			$row->find_replace_links	=	base64_decode($row->find_replace_links);
			$row->front_page_keyword	=	base64_decode($row->front_page_keyword);
		} else {
			$row->published 	= 1;
			$row->publish_time = 0;
			$row->publish_down = JText::_('Never');
			$row->time_update	=	60;	
			$row->numbercontent = 10;
			$row->get_img		=	1;
			$row->maxpixel		=	60;
		}	
		
		return $row;		
	}
	
	
	function getLists(){
		
		$db			=	&JFactory::getDBO();
		
		$cid		= JRequest::getVar( 'cid', array(0), '', 'array' );
	
		JArrayHelper::toInteger($cid, array(0));
		$doTask 	= JRequest::getCmd('task',null);
		$edit		=	strtolower($doTask) == 'news.edit';
		$sectionid	=	0;
	
		$row =& JTable::getInstance('YOS_News_Crawler','Table');
		// load the row from the db table
		if ($edit)
			$row->load( $cid[0] );
		
		$config 	= &JComponentHelper::getParams('com_yos_news_crawler');
		$data_type 	= $config->get('data_type');
		
		if ($data_type == 'joomla') {			
			$javascript = "onchange=\"changeDynaList( 'catid', sectioncategories, document.adminForm.sectionid.options[document.adminForm.sectionid.selectedIndex].value, 0, 0);\"";
	
			$query = 'SELECT s.id, s.title' .
					' FROM #__sections AS s' .
					' ORDER BY s.ordering';
			$db->setQuery($query);
	
			$sections[] = JHTML::_('select.option', '-1', '- '.JText::_('Select Section').' -', 'id', 'title');
			$sections[] = JHTML::_('select.option', '0', JText::_('Uncategorized'), 'id', 'title');
			$sections = array_merge($sections, $db->loadObjectList());
			$lists['sectionid'] = JHTML::_('select.genericlist',  $sections, 'sectionid', 'class="inputbox" size="1" '.$javascript, 'id', 'title', intval($row->sectionid));
			foreach ($sections as $section)
			{
				$section_list[] = (int) $section->id;
				// get the type name - which is a special category
				if ($row->sectionid) {
					if ($section->id == $row->sectionid) {
						$contentSection = $section->title;
					}
				} else {
					if ($section->id == $sectionid) {
						$contentSection = $section->title;
					}
				}
			}
	
			$sectioncategories = array ();
			$sectioncategories[-1] = array ();
			$sectioncategories[-1][] = JHTML::_('select.option', '-1', JText::_( 'Select Category' ), 'id', 'title');
			$section_list = implode('\', \'', $section_list);
	
			$query = 'SELECT id, title, section' .
					' FROM #__categories' .
					' WHERE section IN ( \''.$section_list.'\' )' .
					' ORDER BY ordering';
			$db->setQuery($query);
			$cat_list = $db->loadObjectList();
	
			// Uncategorized category mapped to uncategorized section
			$uncat = new stdClass();
			$uncat->id = 0;
			$uncat->title = JText::_('Uncategorized');
			$uncat->section = 0;
			$cat_list[] = $uncat;
			foreach ($sections as $section)
			{
				$sectioncategories[$section->id] = array ();
				$rows2 = array ();
				foreach ($cat_list as $cat)
				{
					if ($cat->section == $section->id) {
						$rows2[] = $cat;
					}
				}
				foreach ($rows2 as $row2) {
					$sectioncategories[$section->id][] = JHTML::_('select.option', $row2->id, $row2->title, 'id', 'title');
				}
			}
			$sectioncategories['-1'][] = JHTML::_('select.option', '-1', JText::_( 'Select Category' ), 'id', 'title');
			$categories = array();
			foreach ($cat_list as $cat) {
				if($cat->section == $row->sectionid)
					$categories[] = $cat;
			}
	
			$categories[] = JHTML::_('select.option', '-1', JText::_( 'Select Category' ), 'id', 'title');
			$lists['catid'] = JHTML::_('select.genericlist',  $categories, 'catid', 'class="inputbox" size="1"', 'id', 'title', intval($row->catid));		
			
			$lists['sectioncategories']		=	$sectioncategories;
			
			//created_by
			$lists['created_by']		=	JHTML::_('list.users', 'created_by', $row->created_by);
		}else {
			$option_ = array(); //prevent problems
 
			$option_['driver']   = $config->get('d_w_driver');       	// Database driver name
			$option_['host']     = $config->get('d_w_host');    		// Database host name
			$option_['user']     = $config->get('d_w_user');  	    	// User for database authentication
			$option_['password'] = $config->get('d_w_password');  		// Password for database authentication
			$option_['database'] = $config->get('d_w_database');  	  	// Database name
			$option_['prefix']   = $config->get('d_w_prefix');          // Database prefix (may be empty)
			
			if (empty($option_['user']) || empty($option_['password']) || empty($option_['database']))
				return ;
			
			$db_	= &JDatabase::getInstance( $option_ );
			
			if (!empty($db_->message)) {
				echo '<h2>'.$db_->message.'</h2>';
				return ;
			}
			
			if ($data_type == 'drupal') {
				$query = 'SELECT a.type, a.name' .
						' FROM #__node_type AS a'
						;
				$db_->setQuery($query);
					
				$content_types[] 		= JHTML::_('select.option', '-1', '- '.JText::_('Select Content Type').' -', 'type', 'name');
				if ($items	= $db_->loadObjectList())
					$content_types = array_merge($content_types, $items);
				$lists['content_type'] 	= JHTML::_('select.genericlist',  $content_types, 'content_type', 'class="inputbox" size="1" ', 'type', 'name', $row->content_type);
				
				$mitems	= $this->getCategories($db_);
				$lists['catid']	= null;
				if ($mitems) {
					$cat[] 			= JHTML::_('select.option', '0', '- '.JText::_( 'Select Category' ).' -', 'id', 'name');
					$mitems 		= array_merge($cat, $mitems);
					$lists['catid']	= JHTML::_('select.genericlist',  $mitems, 'catid', 'class="inputbox" size="1"', 'id', 'name', intval($row->catid).','.base64_encode($row->catname));
				}
				
				//created_by
				$query = 'SELECT a.uid, a.name' .
						' FROM #__users AS a WHERE a.uid <> 0'
						;
				$db_->setQuery($query);
							
				$created_by 			= $db_->loadObjectList();
				$lists['created_by'] 	= JHTML::_('select.genericlist',  $created_by, 'created_by', 'class="inputbox" size="1" ', 'uid', 'name', $row->created_by);			
				
				//Input format
				$query = 'SELECT a.format, a.name' .
						' FROM #__filter_formats AS a'
						;
				$db_->setQuery($query);
				
				$input_format[] 		= JHTML::_('select.option', '0', '- '.JText::_( 'Select Input Format' ).' -', 'format', 'name');
				if ($items	= $db_->loadObjectList())
					$input_format = array_merge($input_format, $items);
				$lists['input_format'] 	= JHTML::_('select.genericlist',  $input_format, 'input_format', 'class="inputbox" size="1" ', 'format', 'name', $row->input_format);
				
				//Comment
				$comment[0]->id		= 0;
				$comment[0]->name	= 'Disabled';
				$comment[1]->id		= 1;
				$comment[1]->name	= 'Read only';
				$comment[2]->id		= 2;
				$comment[2]->name	= 'Read/Write';
				$lists['comment'] 	= JHTML::_('select.genericlist',  $comment, 'comment', 'class="inputbox" size="1" ', 'id', 'name', $row->comment);
			}else {
				$query = 'SELECT a.type, a.name' .
						' FROM #__node_type AS a'
						;
				$db_->setQuery($query);
					
				$content_types[0] 		= JHTML::_('select.option', '-1', '- '.JText::_('Select Content Type').' -', 'type', 'name');
				$content_types[1]->type	= 'post';
				$content_types[1]->name	= 'Post';
				$content_types[2]->type	= 'page';
				$content_types[2]->name	= 'Page';
				$lists['content_type'] 	= JHTML::_('select.genericlist',  $content_types, 'content_type', 'class="inputbox" size="1" ', 'type', 'name', $row->content_type);
								
				$where 	= ' WHERE a.term_id = b.term_id AND a.taxonomy = '.$db_->Quote('category');
				$query 	= ' SELECT a.term_taxonomy_id AS id, a.parent, b.name'
						.' FROM '.$db_->NameQuote('#__wp_term_taxonomy').' AS a '				
						.', '.$db_->NameQuote('#__wp_terms').' AS b '
						.$where
						;
				$db_->setQuery($query);
				
				$categories	= $db_->loadObjectList();
				
				$children 	= array();
				$mitems 	= array();
				if ($categories){
					foreach ( $categories as $v ){						
						$pt 		= $v->parent;
						$list 		= @$children[$pt] ? $children[$pt] : array();
						array_push( $list, $v );
						$children[$pt] = $list;
					}
					$list = JHTML::_('menu.treerecurse', 0, '', array(), $children, 9999, 0, 0 );
			
					foreach ( $list as $item ) {
						$mitems[] = JHTML::_('select.option',  $item->id.','.base64_encode($item->treename), '&nbsp;&nbsp;&nbsp;'.$item->treename );
					}
				}
				
				$lists['catid']	= null;
				if ($mitems) {
					$cat[] 			= JHTML::_('select.option', '0', '- '.JText::_( 'Select Category' ).' -', 'value', 'text');
					$mitems 		= array_merge($cat, $mitems);
					$lists['catid']	= JHTML::_('select.genericlist',  $mitems, 'catid', 'class="inputbox" size="1"', 'value', 'text', $row->catid.','.base64_encode($row->catname));
				}
				
				//created_by
				$query = 'SELECT a.ID AS id, a.user_login AS name' .
						' FROM #__wp_users AS a WHERE a.ID <> 0'
						;
				$db_->setQuery($query);
							
				$created_by 			= $db_->loadObjectList();
				$lists['created_by'] 	= JHTML::_('select.genericlist',  $created_by, 'created_by', 'class="inputbox" size="1" ', 'id', 'name', $row->created_by);
				
				//Comment
				$comment 				= ($row->comment == 1) ? 1 : 0;
				$lists['comment'] 		= JHTML::_('select.booleanlist',  'comment', 'class="inputbox"', $comment);
				
				//Ping
				$ping 					= ($row->input_format == 1) ? 1 : 0;
				$lists['ping'] 			= JHTML::_('select.booleanlist',  'input_format', 'class="inputbox"', $ping);
			}
		}
		
		$category = ($row->id) ? $row->category : 1;
		$lists['category'] 		= JHTML::_('select.booleanlist',  'category', 'class="inputbox"', $category );	
		
		$get_img = ($row->id) ? $row->get_img : 0;
		$lists['get_img'] 		= JHTML::_('select.booleanlist',  'get_img', 'class="inputbox"', $get_img );		
		
		// build the html radio buttons for published		
		$published = ($row->id) ? $row->published : 1;
		$lists['published'] 		= JHTML::_('select.booleanlist',  'published', 'class="inputbox"', $published );
		
		// build the html radio buttons for category ads	
		$catads = ($row->id) ? $row->catads : 1;
		$lists['catads'] 		= JHTML::_('select.booleanlist',  'catads', 'class="inputbox"', $catads, 'Bottom of Intro', 'Top of Intro' );
		
		// build the html radio buttons for Extend Title Position	
		$title_ext_pos = ($row->id) ? $row->title_ext_pos : 1;
		$lists['title_ext_pos'] 		= JHTML::_('select.booleanlist',  'title_ext_pos', 'class="inputbox"', $title_ext_pos, 'Last of title', 'First of title' );
		
		// build the html radio buttons for option readmore	
		$readmore = ($row->id) ? $row->readmore : 0;
		$lists['readmore'] 		= JHTML::_('select.booleanlist',  'readmore', 'class="inputbox"', $readmore );
		
		//access
		$query	=	"SELECT * FROM #__groups";
		$db->setQuery($query);
		$group	=	$db->loadObjectList();
		
		$lists['access']			=	JHTML::_('select.genericlist', $group, 'access', 'class="inputbox" size="1"', 'id', 'name', $row->access);
		
		## Section & Category query
		$query = 'SELECT CONCAT_WS(",",s.id,c.id) AS `value`, CONCAT_WS(" / ", s.title, c.title) AS `text`' .
				' FROM #__sections AS s' .
				' INNER JOIN #__categories AS c ON c.section = s.id' .
				' WHERE s.scope = "content"' .
				' ORDER BY s.title, c.title';
		$db->setQuery($query);

		// Add a row for uncategorized content
		$uncat	= JHTML::_('select.option', '0,0', JText::_('UNCATEGORIZED'));
		$rows	= $db->loadObjectList();
		array_unshift($rows, $uncat);
		// build the html select list
		$lists['sectcat'] = JHTML::_('select.genericlist', $rows, 'sectcat', 'class="inputbox" size="10"', 'value', 'text', NULL);
		
		// build the html radio buttons for option readmore	
		$cut_content = ($row->id) ? $row->cut_content : 0;
		$lists['cut_content'] 		= JHTML::_('select.booleanlist',  'cut_content', 'class="inputbox"', $cut_content );
		
		// resize images
		$resizeimage = ($row->id) ? $row->resizeimage : 0;
		$lists['resizeimage']		= JHTML::_('select.booleanlist',  'resizeimage', 'class="inputbox"', $resizeimage );
		
		// Select plug-in for chart
		$query = "SELECT id, name FROM #__plugins WHERE folder = 'yos_crawler' AND published = 1";
		$db->setQuery($query);		
		$plugin = $db->loadObjectList();
		$html	= '<select name="pid" id="pid">';
		$html	.='<option value="0">------------------</option>';
		$html	.= JHTML::_('select.options', $plugin, 'id', 'name', $row->pid );
		$html	.= '</select>';
		$lists['plugin_id']			= $html;
		
		// select dataway
		$dataway	=	($row->id) ? $row->dataway : 0;
		$obj		= 	new JObject();
		$obj->value	=	0;
		$obj->text	=	'MainIntro and Fulltext';
		$option[]	=	$obj;
		$obj		= 	new JObject();
		$obj->value	=	1;
		$obj->text	=	'Intro and Fulltext';
		$option[]	=	$obj;
		$obj		= 	new JObject();
		$obj->value	=	2;
		$obj->text	=	'Introtext and Cut text';
		$option[]	=	$obj;
		$obj		= 	new JObject();
		$obj->value	=	3;
		$obj->text	=	'MainIntro and Cut text';
		$option[]	=	$obj;
		$lists['dataway']		=	JHTML::_('select.genericlist', $option, 'dataway', 'class="inputbox" size="4"', 'value', 'text', $dataway);
		
		// pagebreak
		$lists['pagebreak']		=	JHTML::_('select.booleanlist',  'pagebreak', 'class="inputbox"', $row->pagebreak );
		
		// validate cookie
		$lists['cookie']		=	JHTML::_('select.booleanlist',  'validate_cookie', 'class="inputbox"', $row->validate_cookie );
		
		// rewrite code
		$lists['rewrite']		=	JHTML::_('select.booleanlist',  'rewrite', 'class="inputbox"', $row->rewrite );
		
		// front page
		$lists['front-page']	=	JHTML::_('select.booleanlist',  'front_page', 'class="inputbox"', $row->front_page );
		
		return $lists;
	}

	function getScript(){
		
		$script=
		"
			google.load(\"language\", \"1\");
			google.setOnLoadCallback(init);
			
			function init() 
			{				
				var t_from = document.getElementById('t_from');
				var t_to = document.getElementById('t_to');
				for (l in google.language.Languages) 
				{
					var lng = l.toLowerCase();
					lng 		= lng.substring(0,1).toUpperCase()+lng.substring(1,lng.length);
					var lngCode = google.language.Languages[l];
					if (google.language.isTranslatable(lngCode)) 
					{
						t_from.options.add(new Option(lng, lngCode));
						t_to.options.add(new Option(lng, lngCode));
					}
				}
			}";
		return $script;
	}
	
	function getCategories($db_)
	{
		$user 	= &JFactory::getUser();
				
		$query 	= ' SELECT a.cid AS id, a.parent, b.title AS name'
				.' FROM '.$db_->NameQuote('#__category_hierarchy').' AS a '			
				.', '.$db_->NameQuote('#__node').' AS b '
				.' WHERE a.cid = b.nid AND a.parent <> 0'			
				;
		$db_->setQuery($query);
		
		$categories	= $db_->loadObjectList();
		
		if ($categories){
			$mitems = array();
	
			foreach ( $categories as $i=>$item ) {
				$mitems[$i]->id 	= $item->id.','.base64_encode($item->name);
				$mitems[$i]->name = $item->name;
			}
			
			return $mitems;
		}
		
		return false;
	}
}